package leo.dao.ejb3;

import java.util.ArrayList;
import java.util.Iterator;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import leo.entities.Word;
import leo.transfers.WordTo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Leo
 */
@Stateless
public class WordDaoEjb3Bean implements WordDaoEjb3 {

    @PersistenceContext
    private EntityManager em;

    private static final Logger logger = LoggerFactory.getLogger(WordDaoEjb3Bean.class);
    
    @Override
    public WordTo getWordByEnglish(String english) {
        
        logger.debug("查询的单词是：{}", english);
        
        WordTo wordTo = null;
        
        Query query = em.createNamedQuery("Word.findByEnglish");
        query.setParameter("english", english);

        if (!query.getResultList().isEmpty()) {
            Word word = (Word) query.getResultList().get(0);
            wordTo = new WordTo(word.getWordId(), word.getEnglish(), word.getChinese());
        }
        return wordTo;
    }

    @Override
    public ArrayList<WordTo> getWordsByEnglish(String english) {

        logger.debug("查询的单词是：{}", english);
        
        ArrayList<WordTo> list = null;
        Query query = em.createNamedQuery("Word.findByEnglish");
        query.setParameter("english", english);
        Iterator words = query.getResultList().iterator();

        list = new ArrayList<WordTo>();

        while (words.hasNext()) {
            Word word = (Word) words.next();
            WordTo wordTo = new WordTo(word.getWordId(), word.getEnglish(), word.getChinese());
            list.add(wordTo);
        }
        return list;
    }
}